<template>
  <div class="page-container">
    <div style="flex: 1; overflow-y: auto;">
      <!-- 顶部操作栏 -->
      <div style="display: flex; justify-content: space-between; align-items: center; color: #eaeaea; margin-bottom: 20px;">
        <div style="display: flex; gap: 10px;">
          <el-button 
            icon="el-icon-upload2" 
            size="medium"
            @click="showUploadDialog = true"
            style="background-color: black;color: white;padding: 0.65rem 1rem; border-radius: 6px; border: none;">
            上传文件
          </el-button>
          <el-button 
            icon="el-icon-upload" 
            size="medium"
            @click="showBatchUploadDialog = true"
            style="background-color: #409EFF;color: white;padding: 0.65rem 1rem; border-radius: 6px; border: none;">
            批量上传
          </el-button>
          <el-button 
            icon="el-icon-delete" 
            size="medium"
            @click="batchDelete"
            :disabled="selectedFiles.length === 0"
            style="background-color: #F56C6C;color: white;padding: 0.65rem 1rem; border-radius: 6px; border: none;">
            批量删除
          </el-button>
        </div>
        
        <div style="display: flex; align-items: center; gap: 10px;">
          <input 
            type="text" 
            v-model="searchName"
            placeholder="请输入文件名称"
            @keyup.enter="handleSearch"
            style="width: 256px; height: 40px; outline: none; border: none; background-color: rgb(242,243,247); border-radius: 20px; padding: 8px 32px 8px 20px; font-size: 14px;">
          <el-button 
            icon="el-icon-search" 
            @click="handleSearch"
            style="background-color: #67C23A;color: white;padding: 0.65rem 1rem; border-radius: 6px; border: none;">
            搜索
          </el-button>
        </div>
      </div>

      <!-- 文件列表标题 -->
      <div style="display: flex; justify-content: space-between; align-items: center; padding: 5px 5px;">
        <div>PDF文件列表</div>
        <div class="select-button" style="background-color: #f2f3f7; padding: 5px 10px; border-radius: 6px; overflow: hidden">
          <el-badge is-dot>
            <i class="el-icon-select" style="font-size: 16px;margin: 0 6px 0 3px"></i>
            <span style="font-size: 16px;">筛选</span>
          </el-badge>
        </div>
      </div>

      <!-- 文件列表表格 -->
      <div style="width:100%; display: flex; justify-content: center;align-items: center;border-radius: 10px;margin: 10px 0; overflow: hidden;">
        <el-table 
          :data="pdfList" 
          stripe 
          style="width: 100%; height: auto; table-layout: fixed;"
          highlight-current-row 
          show-overflow-tooltip
          header-row-class-name="custom-class"
          @selection-change="handleSelectionChange"
          :header-cell-style="{
            background: 'rgba(239,240,246,0.7)',
            color: 'black',
            height: '35px',
          }">
          
          <el-table-column type="selection" width="55"></el-table-column>
          
          <el-table-column label="文件名称" min-width="200">
            <template v-slot="scope">
              <div style="display: flex; align-items: center; overflow: hidden;">
                <img src="@/assets/icon/pdf-red.png"
                     alt=""
                     style="width: 28px; height: 28px; vertical-align: middle; margin-right: 10px; flex-shrink: 0;"/>
                <span style="color: black; font-family: 'Comic Sans MS', sans-serif; font-size: 14px; vertical-align: middle;
                           flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: inline-block;">
                  {{ scope.row.name }}
                </span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="父文件夹" width="150">
            <template v-slot="scope">
              <div style="color: black; font-family: 'Comic Sans MS', sans-serif; font-size: 14px;">
                {{ scope.row.parentFolderName || '根目录' }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="下载链接" min-width="200">
            <template v-slot="scope">
              <div style="color: #409EFF; font-family: 'Comic Sans MS', sans-serif; font-size: 14px; word-break: break-all;">
                {{ scope.row.downloadUrl }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="预览链接" min-width="200">
            <template v-slot="scope">
              <div style="color: #67C23A; font-family: 'Comic Sans MS', sans-serif; font-size: 14px; word-break: break-all;">
                {{ scope.row.previewUrl }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="150">
            <template v-slot="scope">
              <el-button-group>
                <el-button 
                  type="primary" 
                  icon="el-icon-view" 
                  plain 
                  circle
                  @click="previewFile(scope.row)"
                  title="预览">
                </el-button>
                <el-button 
                  type="success" 
                  icon="el-icon-download" 
                  plain 
                  circle
                  @click="downloadFile(scope.row)"
                  title="下载">
                </el-button>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  plain 
                  circle
                  @click="deleteFile(scope.row)"
                  title="删除">
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
          
          <!-- 自定义空数据时展示的内容 -->
          <template #empty>
            <div style="width:100%; height: calc(100vh - 300px); display: flex; justify-content: center; align-items: center">
              <el-empty :image="require('@/assets/svg/empty.svg')" description="嗷呜~ 暂无数据" :image-size="100"/>
            </div>
          </template>
        </el-table>
      </div>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
          @size-change="handlePageSizeChange"
          @current-change="handlePageNumChange"
          :current-page="pageNum"
          :page-sizes="[8, 9, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- 单个文件上传对话框 -->
    <el-dialog
      title="上传PDF文件"
      :visible.sync="showUploadDialog"
      width="500px"
      :before-close="handleCloseUploadDialog">
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :http-request="uploadFile"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :file-list="uploadFileList"
        accept=".pdf"
        :limit="1">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传pdf文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showUploadDialog = false">取 消</el-button>
        <el-button type="primary" @click="showUploadDialog = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 批量文件上传对话框 -->
    <el-dialog
      title="批量上传PDF文件"
      :visible.sync="showBatchUploadDialog"
      width="600px"
      :before-close="handleCloseBatchUploadDialog">
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :http-request="batchUploadFiles"
        :before-upload="beforeBatchUpload"
        :on-success="handleBatchUploadSuccess"
        :on-error="handleBatchUploadError"
        :file-list="batchUploadFileList"
        accept=".pdf"
        multiple
        :limit="10">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传pdf文件，最多10个文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showBatchUploadDialog = false">取 消</el-button>
        <el-button type="primary" @click="showBatchUploadDialog = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'SystemPdfPage',
  data() {
    return {
      pdfList: [],
      selectedFiles: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      searchName: '',
      showUploadDialog: false,
      showBatchUploadDialog: false,
      uploadFileList: [],
      batchUploadFileList: [],
    };
  },
  methods: {
    // 加载PDF文件列表
    loadPdfList() {
      const params = {
        PageNum: this.pageNum,
        PageSize: this.pageSize
      };
      
      if (this.searchName) {
        params.name = this.searchName;
      }

      request.get('/system_pdf/page', { params })
        .then(res => {
          if (res.code === '200') {
            this.pdfList = res.data.records || [];
            this.total = res.data.total || 0;
          } else {
            this.$message.error(res.msg || '查询失败');
          }
        })
        .catch(error => {
          console.error('查询失败:', error);
          this.$message.error('查询失败');
        });
    },

    // 搜索
    handleSearch() {
      this.pageNum = 1;
      this.loadPdfList();
    },

    // 分页处理
    handlePageNumChange(pageNum) {
      this.pageNum = pageNum;
      this.loadPdfList();
    },

    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageNum = 1;
      this.loadPdfList();
    },

    // 选择处理
    handleSelectionChange(selection) {
      this.selectedFiles = selection;
    },

    // 删除单个文件
    deleteFile(file) {
      this.$confirm('确定要删除这个文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.delete(`/system_pdf/delete/${file.spid}`)
          .then(res => {
            if (res.code === '200') {
              this.$message.success('删除成功');
              this.loadPdfList();
            } else {
              this.$message.error(res.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除失败:', error);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 批量删除
    batchDelete() {
      if (this.selectedFiles.length === 0) {
        this.$message.warning('请选择要删除的文件');
        return;
      }

      this.$confirm(`确定要删除选中的 ${this.selectedFiles.length} 个文件吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedFiles.map(file => file.spid);
        request.delete('/system_pdf/delete/batch', { data: ids })
          .then(res => {
            if (res.code === '200') {
              this.$message.success('批量删除成功');
              this.selectedFiles = [];
              this.loadPdfList();
            } else {
              this.$message.error(res.msg || '批量删除失败');
            }
          })
          .catch(error => {
            console.error('批量删除失败:', error);
            this.$message.error('批量删除失败');
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 预览文件
    previewFile(file) {
      if (file.previewUrl) {
        window.open(file.previewUrl, '_blank');
      } else {
        this.$message.warning('预览链接不可用');
      }
    },

    // 下载文件
    downloadFile(file) {
      if (file.downloadUrl) {
        const link = document.createElement('a');
        link.href = file.downloadUrl;
        link.download = file.name;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
        this.$message.warning('下载链接不可用');
      }
    },

    // 上传前检查
    beforeUpload(file) {
      const isPDF = file.type === 'application/pdf';
      const isLt100M = file.size / 1024 / 1024 < 100;

      if (!isPDF) {
        this.$message.error('只能上传PDF文件!');
        return false;
      }
      if (!isLt100M) {
        this.$message.error('文件大小不能超过100MB!');
        return false;
      }
      return true;
    },

    // 单个文件上传
    uploadFile(options) {
      const formData = new FormData();
      formData.append('file', options.file);

      request.post('/system_pdf/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.code === '200') {
          this.$message.success('上传成功');
          this.loadPdfList();
          options.onSuccess(res);
        } else {
          this.$message.error(res.msg || '上传失败');
          options.onError(new Error(res.msg || '上传失败'));
        }
      }).catch(error => {
        console.error('上传失败:', error);
        this.$message.error('上传失败');
        options.onError(error);
      });
    },

    // 批量上传前检查
    beforeBatchUpload(file) {
      return this.beforeUpload(file);
    },

    // 批量文件上传
    batchUploadFiles(options) {
      const formData = new FormData();
      formData.append('files', options.file);

      request.post('/system_pdf/batchUpload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.code === '200') {
          this.$message.success('批量上传成功');
          this.loadPdfList();
          options.onSuccess(res);
        } else {
          this.$message.error(res.msg || '批量上传失败');
          options.onError(new Error(res.msg || '批量上传失败'));
        }
      }).catch(error => {
        console.error('批量上传失败:', error);
        this.$message.error('批量上传失败');
        options.onError(error);
      });
    },

    // 上传成功处理
    handleUploadSuccess(response, file, fileList) {
      this.uploadFileList = fileList;
    },

    // 上传失败处理
    handleUploadError(err, file, fileList) {
      this.uploadFileList = fileList;
    },

    // 批量上传成功处理
    handleBatchUploadSuccess(response, file, fileList) {
      this.batchUploadFileList = fileList;
    },

    // 批量上传失败处理
    handleBatchUploadError(err, file, fileList) {
      this.batchUploadFileList = fileList;
    },

    // 关闭上传对话框
    handleCloseUploadDialog() {
      this.showUploadDialog = false;
      this.uploadFileList = [];
    },

    // 关闭批量上传对话框
    handleCloseBatchUploadDialog() {
      this.showBatchUploadDialog = false;
      this.batchUploadFileList = [];
    },
  },
  mounted() {
    this.loadPdfList();
  }
};
</script>

<style scoped>
.custom-class {
  font-size: 14px;
  font-weight: bold;
  height: 54px;
}

.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.pagination-area {
  padding: 10px 0;
  display: flex;
  justify-content: center;
  border-top: 1px solid #e0e0e0;
  background: #fff;
}

.select-button:hover {
  background-color: black;
}

.upload-demo {
  text-align: center;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 7px;
}

.dialog-footer {
  text-align: right;
}
</style> 